
// http://125.94.106.113:81/
// http://125.94.106.113:82
// let BASE_URL = 'https://talk.shuyeit.com:22301/api'
// export const RESOURCE_URL = 'https://talk.shuyeit.com:22301'
// let BASE_URL = 'http://125.94.106.113:81'
// export const RESOURCE_URL = 'http://125.94.106.113:82'
let BASE_URL = 'https://www.aiplxt.cn:82/api'
export const RESOURCE_URL = 'https://www.aiplxt.cn:82'

export function setBaseURL(baseURL) {
  BASE_URL = baseURL || ''
}

export function getBaseURL() {
  if (BASE_URL) return BASE_URL
  try {
    const storageBase = uni.getStorageSync('BASE_URL')
    return storageBase || ''
  } catch (_) {
    return ''
  }
}

function normalizeUrl(baseURL, url) {
  if (!baseURL) return url
  // 合并多余斜杠，但保留协议部分
  const joined = baseURL.replace(/\/$/, '') + '/' + url.replace(/^\//, '')
  return joined.replace(/([^:])\/\/+/, '$1/')
}

function buildHeaders(extra) {
  const headers = {
    'Content-Type': 'application/json'
  }
  if (extra) {
    for (const key in extra) headers[key] = extra[key]
  }
  // token 注入
  try {
    const token = uni.getStorageSync('token')
    if (token) headers['Authorization'] = `${token}`
  } catch (_) {}
  return headers
}

export function request(options) {
  const {
    url,
    method = 'GET',
    data,
    headers,
    timeout = 15000,
    showLoading = false,
    baseURLOverride
  } = options

  const finalURL = normalizeUrl(baseURLOverride !== undefined ? baseURLOverride : getBaseURL(), url)
  const finalHeaders = buildHeaders(headers)

  return new Promise((resolve, reject) => {
    if (showLoading) {
      uni.showLoading({ title: '加载中', mask: true })
    }

    uni.request({
      url: finalURL,
      method: method,
      data: data,
      header: finalHeaders,
      timeout,
      success: (res) => {
        console.log('接口响应：',res)
        const status = res.statusCode || 0
        const respData = res.data
        if (status === 200 && respData.code === 200) {
          resolve(respData.data || respData.message)
          return
        } else if (status === 401) {
          // 跳转到登录页面
          // uni.showToast({ title: '登录失效', icon: 'none' })
          uni.setStorageSync('token', '')
          setTimeout(() => {
            uni.reLaunch({ url: '/pages/login/index' })
          }, 1500)
          reject(new Error('401'))
          return
        }
        const msg = (respData && (respData.message || respData.msg)) || `请求失败(${status})`
        uni.showToast({ title: String(msg), icon: 'none' })
        reject(new Error(String(msg)))
      },
      fail: (err) => {
        uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' })
        reject(err)
      },
      complete: () => {
        if (showLoading) {
          uni.hideLoading()
        }
      }
    })
  })
}

export function get(url, params, opts) {
  // 将 params 作为 query 拼接
  const query = params
    ? '?' + Object.keys(params)
        .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`)
        .join('&')
    : ''
  return request({ url: url + query, method: 'GET', ...(opts || {}) })
}

export function post(url, data, opts) {
  return request({ url, method: 'POST', data, ...(opts || {}) })
}

export function put(url, data, opts) {
  return request({ url, method: 'PUT', data, ...(opts || {}) })
}

export function del(url, opts) {
  return request({ url, method: 'DELETE', ...(opts || {}) })
}

export function patch(url, data, opts) {
  return request({ url, method: 'PATCH', data, ...(opts || {}) })
}


